<template>
    <el-dialog
        :title="!dataForm.id ? $t('handle.add') : $t('handle.update')"
        :close-on-click-modal="false"
        :visible.sync="visible">
    <div v-loading = loading>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="150px">
      <el-form-item label="中文名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="app中文名称"></el-input>
      </el-form-item>
      <el-form-item label="文件名" prop="fileName">
        <el-input v-model="dataForm.fileName" placeholder="app文件名"></el-input>
      </el-form-item>
      <el-form-item label="版本号" prop="verNo">
        <el-input v-model="dataForm.verNo" placeholder="app版本号"></el-input>
      </el-form-item>
      <el-form-item label="系统类型" prop="type">
            <el-select style="width: 100%;" v-model="dataForm.type" filterable placeholder="请选择" >
                <el-option v-for="item in typeDicts" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
            </el-select>
      </el-form-item>
      <el-form-item label="下载类型" prop="downloadType">
            <el-select style="width: 100%;" v-model="dataForm.downloadType" filterable placeholder="请选择" @change="disableStstus">
                <el-option v-for="item in downloadTypeDicts" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
            </el-select>
      </el-form-item>
      <el-form-item  v-if="UrlShow" label="下载路径" prop="downloadUrl">
        <el-input v-model="downloadUrl" placeholder="app安装包下载路径" v-bind:redOnly="disabledInput" ></el-input>
        <el-input type="hidden" v-model="dataForm.downloadUrl" placeholder="app安装包下载路径" v-bind:redOnly="disabledInput" ></el-input>
      </el-form-item>
      <el-form-item v-if="!UrlShow" label="下载路径" prop="downloadUrl">
        <el-input v-model="dataForm.downloadUrl" placeholder="app安装包下载路径" v-bind:redOnly="disabledInput" ></el-input>
      </el-form-item>
      <div class="upload" v-if="show" >
        <el-form-item>
          <el-upload
            ref="upload"
            action="/clientauth/client/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSucess"
            :on-error="handleError"
            :on-exceed="handleExceed"
            :before-upload="beforeAvatarUpload"
            :file-list="fileList"
            :headers="headers"
            :limit="1"
            list-type="picture"
            style="width: 50%;">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传apk/api文件，且不超过100MB</div>
            </el-upload>
        </el-form-item>
      </div>
      <el-form-item label="强制更新" prop="forceFlag">
           <el-select style="width: 100%;" v-model="dataForm.forceFlag" filterable placeholder="请选择">
                <el-option v-for="item in forceFlagDicts" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
            </el-select>
      </el-form-item>
      <el-form-item label="更新内容" prop="updateDetails">
        <el-input v-model="dataForm.updateDetails" placeholder="更新内容"></el-input>
      </el-form-item>
      <el-form-item :label="$t('tabble.sort')" prop="sort">
        <el-input v-model="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item>
    </el-form>
    <div style="text-align:right;">
    <span slot="footer" class="dialog-footer">
      <el-button @click="callOf()">{{ $t('handle.cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmit()">{{ $t('handle.confirm') }}</el-button>
    </span>
    </div>
    </div>
  </el-dialog>
</template>
<script>
import Vue from "vue";
import { imgUrlHost } from "@/config/env";
export default {
  data() {
    return {
      UrlShow:false,
      imgUrlHost: imgUrlHost,
      downloadUrl:"",
      loading: false,
      headers: {
        Authorization: "Bearer " + Vue.cookie.get("access-token")
      },
      fileList: [],
      picJson: { url: "" },
      disabledInput: false,
      visible: false,
      show: false,
      dataForm: {
        id: "",
        name: "",
        fileName: "",
        verNo: "",
        type: "",
        downloadType: "",
        downloadUrl: "",
        forceFlag: "",
        updateDetails: "",
        sort: ""
      },
      typeDicts: [],
      downloadTypeDicts: [],
      forceFlagDicts: [],
      dataRule: {
        name: [
          { required: true, message: "中文名称不能为空", trigger: "blur" }
        ],
        fileName: [
          { required: true, message: "文件名称不能为空", trigger: "blur" }
        ],
        verNo: [{ required: true, message: "版本号不能为空", trigger: "blur" }],
        type: [
          { required: true, message: "app类型不能为空", trigger: "change" }
        ],
        downloadType: [
          { required: true, message: "app下载类型不能为空", trigger: "change" }
        ],
        downloadUrl: [
          { required: true, message: "app下载路径不能为空", trigger: "blur" }
        ],
        forceFlag: [
          { required: true, message: "强制更新不能为空", trigger: "change" }
        ],
        updateDetails: [
          { required: true, message: "更新内容不能为空", trigger: "blur" }
        ],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }]
      }
    };
  },

  methods: {
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      // 把路径置为空
      this.dataForm.downloadUrl = "";
      this.downloadUrl = "";
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {},
    // 文件上传成功时调用
    handleSucess(response, file, fileList) {
      this.$message({
        message: "文件上传成功",
        type: "success",
        duration: 1500,
        onClose: () => {
          this.dataForm.downloadUrl = response.iconName;
          this.downloadUrl = imgUrlHost + response.iconName;
          this.picJson.url = this.dataForm.downloadUrl;
          this.fileList[0] = this.picJson;
        }
      });
    },
    // 文件上传失败时调用
    handleError(err, file, fileList) {
      this.$message.error("文件上传失败");
    },
    handleExceed(files, fileList) {
      this.$message.error("只能上传一个文件,请先去除原文件");
    },
    beforeAvatarUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isJPG = testmsg === "apk";
      const isPNG = testmsg === "api";
      const isLt2M = file.size / 1024 / 1024 < 100;
      let fileFlag = false;
      if (isJPG || isPNG) {
        fileFlag = true;
      } else {
        this.$message.error("上传文件只能是 apk 格式或 api 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 100MB!");
      }
      return fileFlag && isLt2M;
    },
    disableStstus(val) {
      if (val === "2") {
        // 官网下载，隐藏上传文件控件，可编辑为false
        this.disabledInput = true;
        this.show = false;
      } else {
        this.disabledInput = false;
        this.show = true;
      }
    },
    clearForm() {
      this.dataForm.name = "";
      this.dataForm.fileName = "";
      this.dataForm.verNo = "";
      this.dataForm.type = "";
      this.dataForm.downloadType = "";
      this.dataForm.downloadUrl = "";
      this.dataForm.forceFlag = "";
      this.dataForm.updateDetails = "";
      this.dataForm.sort = "";
      this.downloadUrl = "";
    },
    init(id, typeDicts, downloadTypeDicts, forceFlagDicts) {
      this.typeDicts = typeDicts;
      this.downloadTypeDicts = downloadTypeDicts;
      this.forceFlagDicts = forceFlagDicts;
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
      });
      if (typeof id == "undefined") {
        // 新增
        this.clearForm();
      }
      if (this.dataForm.id) {
        this.$http({
          url: `/dg-ic/ic/app-version/info/${this.dataForm.id}`,
          method: "get",
          params: this.$http.adornParams()
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.UrlShow = data.data.downloadType==1?true:false;

            this.dataForm.name = data.data.name;
            this.dataForm.fileName = data.data.fileName;
            this.dataForm.verNo = data.data.verNo;
            this.dataForm.type = String(data.data.type);
            this.dataForm.downloadType = String(data.data.downloadType);
            this.dataForm.downloadUrl = data.data.downloadUrl;
            this.downloadUrl = imgUrlHost + data.data.downloadUrl;
            this.dataForm.forceFlag = String(data.data.forceFlag);
            this.dataForm.updateDetails = data.data.updateDetails;
            this.dataForm.sort = data.data.sort;
            this.dataForm.updateBy = data.data.updateBy;
            this.dataForm.createBy = data.data.createBy;
          }
        });
      }
    },
    dataFormSubmit() {
      this.$refs["dataForm"].validate(validate => {
        if (validate) {
          this.loading = true;
          this.$http({
            url: `/dg-ic/ic/app-version/${
              !this.dataForm.id ? "save" : "update"
            }`,
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              name: this.dataForm.name,
              fileName: this.dataForm.fileName,
              verNo: this.dataForm.verNo,
              type: this.dataForm.type,
              downloadType: this.dataForm.downloadType,
              downloadUrl: this.dataForm.downloadUrl,
              forceFlag: this.dataForm.forceFlag,
              updateDetails: this.dataForm.updateDetails,
              sort: this.dataForm.sort,
              createBy: this.$store.state.user.id,
              updateBy: this.$store.state.user.id
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.loading = false;
                  this.visible = false;
                  this.$refs[`dataForm`].resetFields();
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
              this.loading = false;
            }
          });
        }
      });
    },
    callOf() {
      this.visible = false;
      this.$refs[`dataForm`].resetFields();
    }
  }
};
</script>
